<template>
  <div class="app-container">
    <basic-container>
      <avue-crud ref="crud"
                 v-model="form"
                 :page="jkdnPage"
                 :data="tableData"
                 :option="tableOption"
                 :table-loading="jkdnLoading"
                 @on-load="getList"
                 @search-change="searchChange"
                 @refresh-change="refreshChange"
                 @row-save="rowSave"
                 @row-del="rowDel">
        <template slot="bcbz"
                  slot-scope="scope">
          <el-tag :type="scope.row.bcbz=='1'?'':'danger'">{{scope.row.bcbz=='1'?"已同步":"未同步"}}</el-tag>
        </template>
        <template slot="sgtzbz"
                  slot-scope="scope">
          <el-tag :type="scope.row.sgtzbz=='1'?'':'danger'">{{scope.row.sgtzbz=='1'?"已同步":"未同步"}}</el-tag>
        </template>
        <template slot="ytjbz"
                  slot-scope="scope">
          <el-tag :type="scope.row.ytjbz=='1'?'':'danger'">{{scope.row.ytjbz=='1'?"已同步":"未同步"}}</el-tag>
        </template>
        <template slot="xqbz"
                  slot-scope="scope">
          <el-tag :type="scope.row.xqbz=='1'?'':'danger'">{{scope.row.xqbz=='1'?"已同步":"未同步"}}</el-tag>
        </template>
        <template slot="shbz"
                  slot-scope="scope">
          <el-tag :type="scope.row.shbz=='1'?'':'danger'">{{scope.row.shbz=='1'?"已同步":"未同步"}}</el-tag>
        </template>
        <template slot="uploadFlag"
                  slot-scope="scope">
          <el-tag :type="scope.row.uploadFlag=='1'?'success':'danger'">{{scope.row.uploadFlag=='1'?"已上传":"未上传"}}</el-tag>
        </template>
        <template slot-scope="scope"
                  slot="menuLeft">
          <el-button icon="el-icon-plus"
                     size="small"
                     type="primary"
                     @click="handleAdd">新增</el-button>
          <el-button icon="el-icon-back"
                     size="small"
                     type="primary"
                     @click="handleBack">返回</el-button>
          <el-button @click="synResult"
                     icon="el-icon-upload"
                     size="small"
                     type="primary">同步结果</el-button>
          <el-button icon="el-icon-upload"
                     size="small"
                     type="primary"
                     @click="uploadSheng">上传省平台</el-button>
        </template>
        <template slot-scope="scope"
                  slot="menuForm">
          <el-button type="primary"
                     size="medium"
                     @click="getIdCard()">识别身份证</el-button>
        </template>
        <template slot-scope="scope"
                  slot="menu"
                  fixed="right">
          <!-- v-if="scope.row.uploadFlag!='1'" -->
          <el-button @click="uploadSheng(scope.row)"
                     icon="el-icon-upload"
                     size="small"
                     type="primary">上传</el-button>
          <el-button @click="printTm(scope.row)"
                     icon="el-icon-upload"
                     size="small"
                     type="primary">打印条码</el-button>
          <el-button @click="rowEdit(scope.row)"
                     icon="el-icon-edit"
                     size="small"
                     type="primary">编辑</el-button>
          <el-button @click="rowDel(scope.row)"
                     icon="el-icon-delete"
                     size="small"
                     type="danger">删除</el-button>
          <el-button @click="rowReport(scope.row)"
                     icon="el-icon-edit"
                     size="small"
                     type="primary">生成报告</el-button>
        </template>
      </avue-crud>
      <el-dialog title="健康档案条纹码"
                 :visible.sync="tmCodeVisible">
        <div style="text-align:center"
             ref="print">
          <!-- //30 22 -->
          <svg id="tmcode"
               style="width:24px;height:12px"></svg>
        </div>
        <span class="dialog-footer"
              style="margin-left:45%">
          <el-button type="primary"
                     @click="myprint">打印</el-button>
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import { timeFormatStr, getAge } from '@/filters/'
import { setStore, getStore } from '@/util/store'
import { getIdCard } from '@/api/cust/base'
import tableOption from '@/const/cust/menu/list'
import { fetchList, synResult, uploadSheng } from '@/api/cust/health/list'
import { addObj } from '@/api/cust/health/jkdn'
import JsBarcode from 'jsbarcode'
import { validatenull } from '@/util/validate'
export default {
  name: 'crud',
  data () {
    return {
      grjbxxid: null,
      url: [],
      searchFrom: {},
      form: {},
      org: {},
      jkdnLoading: false,
      tmCodeVisible: false,
      jkdnPage: {
        total: 0,
        currentPage: 0,
        pageSize: 10
      },
      tableOption: tableOption(this),
      tableData: []
    }
  },
  created () {
    this.org = getStore({ name: 'org' })
    // this.getList(this.jkdnPage)
    var page = getStore({ name: 'currentPage' })
    if (!this.validatenull(page)) {
      this.jkdnPage = page
    }
  },
  mounted: function () { },
  computed: {},

  methods: {
    getObjByIdCard () {
      if (this.validatenull(this.form.sfzhm) || this.form.sfzhm.length != 18) {
        this.$message({
          showClose: true,
          message: '请输入正确的身份证号',
          type: 'error'
        })
        return false
      } else {
        //年龄
        this.form.age = getAge(this.form.sfzhm)
        this.form.csrq = this.form.sfzhm.substr(6, 8)
        this.form.xb =
          parseInt(this.form.sfzhm.substr(16, 1)) % 2 == 0 ? '2' : '1'
      }
    },
    synResult (row) {
      var param = { jgbh: this.org.jgbh }
      if (!this.validatenull(row.grjbxxid)) {
        Object.assign(param, row)
        param.type = 'none'
      } else {
        param.type = 'all'
      }

      this.jkdnLoading = true
      synResult(param)
        .then(res => {
          this.$message({
            showClose: true,
            message: '同步成功',
            type: 'success'
          })
          this.jkdnLoading = false
        })
        .catch(err => {
          this.$message({
            showClose: true,
            message: '同步失败' + err,
            type: 'error'
          })
          this.jkdnLoading = false
        })

      this.getList(this.jkdnPage)
    },
    uploadSheng (row) {
      this.jkdnLoading = true
      var param = { sfzh: "" }
      if (row) {
        param.sfzh = row.sfzhm
      }
      uploadSheng(param).then(res => {
        this.jkdnLoading = false
        if (res.data.code == 0) {
          if (!this.validatenull(res.data.data)) {
            this.$message({
              showClose: true,
              message: "姓名：" + res.data.name + '，上传档案成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$message({
              showClose: true,
              message: '后台批量上传中，请稍候查询',
              type: 'success'
            })
          }
        } else {
          this.$message({
            dangerouslyUseHTMLString: true,
            showClose: true,
            message: res.data.msg,
            type: 'error',
            duration: 5000
          })
        }
      })
      // this.getList(this.jkdnPage, this.searchform)
    },
    //身份证识别仪
    getIdCard () {
      getIdCard().then(res => {
        var result = res.data
        if (typeof res.data == 'object') {
          this.$message.error('身份证识别失败，请重试')
          return
        }

        var data = res.data == null ? '' : res.data.replace(/\\/g, '/')
        try {
          result = JSON.parse(data)
        } catch (e) {
          result = eval('(' + data + ')')
        }
        if (result.ret === 0) {
          console.log(result)
          this.form.name = result.Certificate.Name
          this.form.sfzhm = result.Certificate.IDNumber
          this.form.jkdnxzz = result.Certificate.Address
          this.form.jkdnhjdz = result.Certificate.Address
          this.form.age = getAge(result.Certificate.IDNumber)
        } else {
          this.$message.error('身份证识别失败，请重试')
        }
      })
    },
    //搜索
    searchChange (params) {
      if (!validatenull(params.searchTime)) {
        params.betime = params.searchTime[0]
        params.entime = params.searchTime[1]
        params.searchTime = ''
      }
      this.searchform = params
      this.getList(this.jkdnPage, params)
    },
    //刷新
    refreshChange () {
      this.getList(this.jkdnPage, this.searchform)
    },
    //返回基本信息
    handleBack () {
      this.$router.push(`/cust/records`)
    },
    //新增
    handleAdd: function () {
      this.$refs.crud.rowAdd()
      setTimeout(() => {
        console.log(getStore({ name: 'org' }))
        this.form = getStore({ name: 'org' })
        var date = new Date()
        this.form.jdrq =
          date.getFullYear() +
          '-' +
          (date.getMonth() + 1) +
          '-' +
          date.getDate()
        this.form.dnbh = timeFormatStr(new Date(), 'yyyyMMddhhmmss')
      }, 300)
    },
    rowSave (row, done, loading) {
      row.sfzhm = this.form.sfzhm
      row.cwhmc = row.$cwhmcid
      if (this.validatenull(this.form.sfzhm) || this.form.sfzhm.length != 18) {
        this.$message({
          showClose: true,
          message: '请输入正确的身份证号',
          type: 'error'
        })
        loading()
        return false
      } else {
        addObj(row)
          .then(res => {
            console.log(res)
            if (validatenull(res.data.id)) {
              this.$message({
                showClose: true,
                message: res.data.message,
                type: 'error'
              })
              loading()
            } else {
              this.$message({
                showClose: true,
                message: '添加成功',
                type: 'success'
              })
              setStore({ name: 'jkdn', content: res.data })
              this.printTm(res.data)
              this.getList(this.jkdnPage)
              done()
            }

            // this.$router.push({
            //   path: `/cust/jkdn/${res.data.id}`,
            //   query: {
            //     grjbxxid: res.data.grjbxxid,
            //     id: res.data.id,
            //     sfzh: res.data.sfzhm,
            //     where: true
            //   }
            // })
          })
          .catch(res => {
            this.$message({
              showClose: true,
              message: res.data.message,
              type: 'error'
            })
            loading()
          })
      }
    },
    //删除
    rowDel (row) {
      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (
            row.bcbz == '1' ||
            row.sgtzbz == '1' ||
            row.ytjbz == '1' ||
            row.xqbz == '1' ||
            row.shbz == '1'
          ) {
            this.$message({
              showClose: true,
              message: '删除失败，有结果已同步',
              type: 'error'
            })
          } else {
            this.$message({
              showClose: true,
              message: '删除成功',
              type: 'success'
            })
            // delObj(row.id).then(() => {
            //   this.$message({
            //     showClose: true,
            //     message: '删除成功',
            //     type: 'success'
            //   })
            //   this.getList(this.jkdnPage, this.searchform)
            // })
          }
        })
        .catch(function () { })
    },
    rowEdit (row) {
      setStore({ name: 'jkdn', content: row })
      this.$router.push({
        path: `/cust/jkdn/${row.id}`,
        query: {
          grjbxxid: row.grjbxxid,
          id: row.id,
          sfzh: row.sfzhm
        }
      })
    },
    //跳转报告页面
    rowReport (row) {
      setStore({ name: 'jkdn', content: row })
      this.$router.push({
        path: `/cust/report`,
        query: {
          grjbxxid: row.grjbxxid,
          id: row.id,
          sfzh: row.sfzhm,
          tmcode: row.tmcode
        }
      })
    },
    //获取列表
    getList (page, params = {}) {
      setStore({ name: 'currentPage', content: page })
      this.jkdnLoading = true
      fetchList(
        Object.assign(
          { grjbxxid: this.grjbxxid },
          {
            start: (page.currentPage - 1) * page.pageSize,
            length: page.pageSize
          },
          params
        )
      ).then(res => {
        this.jkdnLoading = false
        this.jkdnPage.total = res.data.recordsTotal
        this.tableData = res.data.data
      })
      this.jkdnLoading = false
    },
    breaks () {
      this.$router.$avueRouter.closeTag()
    },
    printTm (row) {
      this.tmCodeVisible = true
      setTimeout(() => {
        JsBarcode('#tmcode', row.tmcode, {
          height: 65,
          width: 1.4,
          text: row.name + ' ' + row.tmcode,
          fontSize: 16
        })
      }, 300)
    },
    myprint () {
      this.$print(this.$refs.print) // 使用
    }
  }
}
</script>